#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
网站内容收集器 - 主程序
类似RSS订阅，但支持使用浏览器登录并抓取网站内容
"""

import os
import sys
import time
import logging
from datetime import datetime
from pathlib import Path

from apscheduler.schedulers.blocking import BlockingScheduler
from apscheduler.triggers.cron import CronTrigger
from colorama import init, Fore, Style

from src.collector import WebCollector
from src.config_manager import ConfigManager
from src.storage import StorageManager

# 初始化colorama用于彩色输出
init(autoreset=True)

class WebContentCollector:
    """网站内容收集器主类"""
    
    def __init__(self):
        self.setup_logging()
        self.config_manager = ConfigManager()
        self.storage_manager = StorageManager()
        self.collector = WebCollector()
        self.scheduler = BlockingScheduler()
        
    def setup_logging(self):
        """设置日志"""
        log_dir = Path("logs")
        log_dir.mkdir(exist_ok=True)
        
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
            handlers=[
                logging.FileHandler(log_dir / f"collector_{datetime.now().strftime('%Y%m%d')}.log", encoding='utf-8'),
                logging.StreamHandler(sys.stdout)
            ]
        )
        self.logger = logging.getLogger(__name__)
        
    def collect_all_sites(self):
        """收集所有配置的网站内容"""
        print(f"{Fore.GREEN}[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 开始收集网站内容...{Style.RESET_ALL}")
        
        sites = self.config_manager.get_all_sites()
        if not sites:
            print(f"{Fore.YELLOW}警告: 没有配置任何网站{Style.RESET_ALL}")
            return
            
        for site_name, site_config in sites.items():
            try:
                print(f"{Fore.CYAN}正在收集: {site_name}{Style.RESET_ALL}")
                content = self.collector.collect_site(site_config)
                
                if content:
                    self.storage_manager.save_content(site_name, content)
                    print(f"{Fore.GREEN}✓ {site_name} 收集完成，保存了 {len(content)} 条内容{Style.RESET_ALL}")
                else:
                    print(f"{Fore.YELLOW}⚠ {site_name} 没有收集到新内容{Style.RESET_ALL}")
                    
            except Exception as e:
                self.logger.error(f"收集 {site_name} 时出错: {str(e)}")
                print(f"{Fore.RED}✗ {site_name} 收集失败: {str(e)}{Style.RESET_ALL}")
                
        print(f"{Fore.GREEN}[{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}] 本轮收集完成{Style.RESET_ALL}")
        
    def start_scheduler(self):
        """启动定时任务"""
        schedule_config = self.config_manager.get_schedule_config()
        
        # 添加定时任务
        self.scheduler.add_job(
            func=self.collect_all_sites,
            trigger=CronTrigger(
                hour=schedule_config.get('hour', '*'),
                minute=schedule_config.get('minute', '0'),
                second=schedule_config.get('second', '0')
            ),
            id='collect_job',
            name='网站内容收集任务'
        )
        
        print(f"{Fore.GREEN}定时任务已启动，按 Ctrl+C 停止{Style.RESET_ALL}")
        print(f"{Fore.CYAN}调度配置: {schedule_config}{Style.RESET_ALL}")
        
        try:
            self.scheduler.start()
        except KeyboardInterrupt:
            print(f"\n{Fore.YELLOW}收到停止信号，正在关闭...{Style.RESET_ALL}")
            self.scheduler.shutdown()
            
    def run_once(self):
        """立即执行一次收集"""
        self.collect_all_sites()
        
    def show_status(self):
        """显示系统状态"""
        print(f"{Fore.CYAN}=== 网站内容收集器状态 ==={Style.RESET_ALL}")
        
        sites = self.config_manager.get_all_sites()
        print(f"配置的网站数量: {len(sites)}")
        
        for site_name in sites.keys():
            last_update = self.storage_manager.get_last_update_time(site_name)
            if last_update:
                print(f"  - {site_name}: 最后更新 {last_update}")
            else:
                print(f"  - {site_name}: 尚未收集")
                
        schedule_config = self.config_manager.get_schedule_config()
        print(f"定时配置: {schedule_config}")
        
def main():
    """主函数"""
    collector = WebContentCollector()
    
    if len(sys.argv) > 1:
        command = sys.argv[1]
        
        if command == "run":
            collector.run_once()
        elif command == "start":
            collector.start_scheduler()
        elif command == "status":
            collector.show_status()
        else:
            print(f"{Fore.RED}未知命令: {command}{Style.RESET_ALL}")
            print("可用命令:")
            print("  run    - 立即执行一次收集")
            print("  start  - 启动定时任务")
            print("  status - 显示系统状态")
    else:
        print(f"{Fore.CYAN}网站内容收集器{Style.RESET_ALL}")
        print("使用方法:")
        print("  python main.py run    - 立即执行一次收集")
        print("  python main.py start  - 启动定时任务")
        print("  python main.py status - 显示系统状态")
        
if __name__ == "__main__":
    main()